from rest_framework import serializers
from .models import OAAbstractUser,UserStatusChoices,OADepartment
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken



# 重写TokenObtainPairSerializer
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        # 获取用户名（email）和密码
        email = attrs.get('email')
        password = attrs.get('password')

        # 使用 Django 自带的 authenticate 方法来验证用户
        user = authenticate(email=email, password=password)

        if user is not None and user.status == UserStatusChoices.ACTIVE:
            refresh = self.get_token(user)
            return {
                'access': str(refresh.access_token),
                'refresh': str(refresh),
            }
        else:
            raise serializers.ValidationError('Invalid credentials or user is not active')

# 登录序列化器
class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    password = serializers.CharField(max_length=255)

    def validate(self,attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        if email and password:
            user = OAAbstractUser.objects.filter(email=email).first()
            if not user:
                raise serializers.ValidationError('用户不存在')
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')

            if user.status == UserStatusChoices.UNACTIVE:
                raise serializers.ValidationError('用户未激活')
            if user.status == UserStatusChoices.LOCKD:
                raise serializers.ValidationError('用户被锁定')
            attrs['user'] = user
            # 生成 JWT
            refresh = RefreshToken.for_user(user)
            attrs['access_token'] = str(refresh.access_token)
            attrs['refresh_token'] = str(refresh)
        else:
            raise serializers.ValidationError('用户名或密码不能为空')
        return attrs

class DeptSerializer(serializers.ModelSerializer):
    class Meta:
        model = OADepartment
        fields = ['id','name','intro','leader','manage']

class UserSerializer(serializers.ModelSerializer):
    department = DeptSerializer(read_only=True)
    class Meta:
        model = OAAbstractUser
        fields = ['id','email','realname','telephone','department','status','date_joined']